package com.longcai.piaojia.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longcai.piaojia.R;
import com.longcai.piaojia.adapter.DayDaySignAdapter;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.DayDaySignGet;
import com.longcai.piaojia.util.MyToast;
import com.longcai.piaojia.widget.NoScrollListView;
import com.longcai.piaojia.widget.UPMarqueeView;
import com.longcai.piaojia.widget.ViewDayDaySignAdvert;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/2.
 */
public class DayDaySignActivity extends BaseActivity implements View.OnClickListener {

    @BoundView(R.id.dayday_sign_nslv) private NoScrollListView dayday_sign_nslv;
    @BoundView(R.id.dayday_sign_rule_tv) private TextView dayday_sign_rule_tv;
    @BoundView(R.id.dayday_sign_record_tv) private TextView dayday_sign_record_tv;
    @BoundView(R.id.dayday_sign_web_rl) private RelativeLayout dayday_sign_web_rl;
    @BoundView(R.id.dayday_sign_wv) private WebView dayday_sign_wv;
    @BoundView(R.id.dayday_sign_scroll_text_upv) private UPMarqueeView dayday_sign_scroll_text_upv;

    @BoundView(R.id.dayday_sign_top_banner) private ViewDayDaySignAdvert dayday_sign_top_banner;

    private List<View> views = new ArrayList<>();

    private DayDaySignAdapter adapter;

    private List<DayDaySignGet.SignShowEntity> lists = new ArrayList<>();
    private List<DayDaySignGet.ScrollEntity> scrollLists = new ArrayList<>();
    private List<DayDaySignGet.BannerEntity> bannerLists = new ArrayList<>();

    private DayDaySignGet dayDaySignGet = new DayDaySignGet(new AsyCallBack<DayDaySignGet.DayDaySignEntity>(){

        @Override
        public void onSuccess(String toast, int type, DayDaySignGet.DayDaySignEntity dayDaySignEntity) throws Exception {

            //list
            lists.addAll(dayDaySignEntity.signShowEntities);
            adapter.notifyDataSetChanged();

            //这是滚动广告的
            scrollLists.addAll(dayDaySignEntity.scrollEntities);
            setView();
            dayday_sign_scroll_text_upv.setViews(views);

            //banner
            bannerLists.addAll(dayDaySignEntity.bannerEntities);

            if (bannerLists.size() > 1) {

                dayday_sign_top_banner.setIsShow(true);

            }

            if(bannerLists.size()!=0){

                dayday_sign_top_banner.setVisibility(View.VISIBLE);
                dayday_sign_top_banner.setItemList(bannerLists);

            }else{

                dayday_sign_top_banner.setVisibility(View.GONE);

            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {


            MyToast.show(context, toast, MyToast.LENGTH_SHORT);

        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_dayday_sgin);

        setBackTrue();

//        setTitleName(getString(R.string.dayday_sign_title_text));
        setTitleName("天天抽奖赢好礼");
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）

        LinearLayout.LayoutParams layoutParams_rl = (LinearLayout.LayoutParams) dayday_sign_web_rl.getLayoutParams();
        layoutParams_rl.height = width + ScaleScreenHelperFactory.getInstance().getWidthHeight(80);
        dayday_sign_web_rl.setLayoutParams(layoutParams_rl);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) dayday_sign_wv.getLayoutParams();
        layoutParams.height = width + ScaleScreenHelperFactory.getInstance().getWidthHeight(20);
        dayday_sign_wv.setLayoutParams(layoutParams);

        Bundle bundle = getIntent().getExtras();

        String url = bundle.getString("url", "");

        // 支持js
        dayday_sign_wv.getSettings().setJavaScriptEnabled(true);
        dayday_sign_wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        dayday_sign_wv.setWebViewClient(new MyWebViewClient());

        dayday_sign_wv.loadUrl(url);

        Log.e("====url===", getIntent().getExtras().getString("url"));

//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        params.topMargin = -(ScaleScreenHelperFactory.getInstance().getWidthHeight(50));
//        params.gravity = Gravity.RIGHT;
//
//        dayday_sign_rule_iv.setLayoutParams(params);

        dayday_sign_nslv.setDivider(null);

        dayday_sign_nslv.setAdapter(adapter = new DayDaySignAdapter(context, lists));

        dayday_sign_nslv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                startActivity(new Intent(context, GoodsInfoActivity.class).putExtra("id", lists.get(position).id));

            }
        });


        dayDaySignGet.execute(this);


        dayday_sign_rule_tv.setOnClickListener(this);
        dayday_sign_record_tv.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.dayday_sign_rule_tv:

                Bundle bundle = new Bundle();

                bundle.putString("url", Conn.SERVICE + Conn.SIGN_NOTICE);
                bundle.putString("title", "抽奖规则");

                startActivity(new Intent(this, WebActivity.class).putExtras(bundle));

                break;

            case R.id.dayday_sign_record_tv:


                startActivity(new Intent(this, SignRecordActivity.class));

                break;


        }


    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        // 在WebView中而不是默认浏览器中显示页面
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            // 处理电话 短信
            if (url.indexOf("tel:") == 0) {
                String telno = url.substring(4).toString();

                Intent intent = new Intent();
                intent.setAction("android.intent.action.DIAL");
                intent.setData(Uri.parse("tel:" + telno));
                startActivity(intent);

                // Intent intent2 = new Intent(Intent.ACTION_CALL,
                // Uri.parse("tel:" + telno));
                // startActivity(intent2);
            } else if (url.indexOf("sms:") == 0) {
                String smslno = url.substring(4).toString();
                Uri uri = Uri.parse("smsto:" + smslno);
                Intent intent1 = new Intent(Intent.ACTION_SENDTO, uri);
                intent1.putExtra("sms_body", "网站留言：");
                startActivity(intent1);
            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            // view.loadData(errorHtml, "text/html", "UTF-8");

//            web_wv.setBackgroundColor(0);
//            web_wv.setBackgroundResource(R.drawable.wuwangluo);
//
//            view.loadUrl("file:///android_asset/error.html");
//
//            Toast.makeText(getApplicationContext(), "Sorry 网络不通...",
//                    Toast.LENGTH_SHORT).show();

        }

        @Override
        // 加载完成时要做的工作
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);


        }

    }


    /**
     * 初始化需要循环的View
     * 为了灵活的使用滚动的View，所以把滚动的内容让用户自定义
     * 假如滚动的是三条或者一条，或者是其他，只需要把对应的布局，和这个方法稍微改改就可以了，
     */
    private void setView() {
        for (int i = 0; i < scrollLists.size(); i++) {

            final int finalI = i;

            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(context).inflate(R.layout.item_dayday_sign_scroll, null));
            //初始化布局的控件
            TextView tv1 = (TextView) moreView.findViewById(R.id.item_dayday_sign_tv);
            //进行对控件赋值
            tv1.setText(scrollLists.get(finalI).info);
//            if (toplists.size() > i + 1) {
//                //因为淘宝那儿是两条数据，但是当数据是奇数时就不需要赋值第二个，所以加了一个判断，还应该把第二个布局给隐藏掉
////                tv2.setText(toplists.get(i + 1).title.toString());
//            }else {
//                moreView.findViewById(R.id.rl2).setVisibility(View.GONE);
//            }

//            //添加到循环滚动数组里面去
//            moreView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    Bundle bundle = new Bundle();
//                    bundle.putString("title", scrollLists.toplist.get(finalI).title);
//                    bundle.putString("url", Conn.SERVICE + Conn.INDEX_TOPLIST_WEB + "?id=" + home.toplist.get(finalI).id);
//
////                    Log.e("这是头条web地址", Conn.SERVICE + Conn.INDEX_TOPLIST_WEB + "?id=" + home.toplist.get(finalI).id);
//
//                    startActivity(new Intent(getActivity(), WebActivity.class).putExtras(bundle));
//
//                }
//            });

            views.add(moreView);
        }
    }



}
